<?php

namespace common\service\project_warning_rules;

use support\ErrorCode;
use support\SingletonTrait;
use common\model\EntityModel;
use common\service\OptionsService;
use common\exception\LogicException;

/**
 * 剧集封板数量筛选
 */
class EpisodeSealNumberCheck implements ProjectWarningRuleInterface
{

    const CHECK_CODE = 'EPISODE_SEAL_NUMBER_CHECK';

    const NEED_PARAM = ['project_id'];

    use SingletonTrait;

    private $errorMessage = [];


    /**
     * 检查参数是否包含
     * @param $param
     * @return void
     */
    public function paramRequired($param)
    {
        foreach (self::NEED_PARAM as $paramKey) {
            if (!isset($param[$paramKey])) {
                throw new LogicException("param {$paramKey} needed", ErrorCode::DATA_INVALID);
            }
        }
    }

    /**
     * 检查是否满足
     * @param $checkData
     * @return bool
     * @throws \think\Exception
     */
    public function check($checkData)
    {
        $this->paramRequired($checkData);
        $limit = $this->getLimitNumber();
        if ($limit <= 0) {
            return true;
        }
        $queryFields = [
            'id',
            'episode_is_seal',
            'episode_is_show',
        ];
        $episodeList = model(EntityModel::class)
            ->alias('episode')
            ->field(transform_custom_fields($queryFields, 'episode'))
            ->where(['episode.project_id' => $checkData['project_id'], 'episode.module_id' => module_by_code('episode')['id']])
            ->where(['episode.code' => ['LIKE', 'EP%']])
            ->where("episode.json->>'$.episode_is_delete' is null or episode.json->>'$.episode_is_delete' = 'no'")
            ->select();

        $sealNotPlayNum = 0;

        foreach ($episodeList as $episode) {
            if ($episode['episode_is_seal'] === 'yes' && ($episode['episode_is_show'] === 'no' || empty($episode['episode_is_show']))) {
                $sealNotPlayNum += 1;
            }
        }
        $res = $limit <= $sealNotPlayNum;
        if (!$res) {
            $this->errorMessage = [
                "当前项目封板剧集数量不足{$this->getLimitNumber()},可能有断更风险",
            ];
        }

        return $limit <= $sealNotPlayNum;
    }

    /**
     * 限额
     * @return int
     */
    private function getLimitNumber()
    {
        return intval(OptionsService::getInstance()->getOptionsConfigItemData('project_warning_check', 'episode_min_seal_not_play_number'));
    }

    /**
     * 获取错误信息
     * @return array
     */
    public function getErrorMessage()
    {
        return $this->errorMessage;
    }

    /**
     * @inheritDoc
     */
    public function getCheckCode()
    {
        return self::CHECK_CODE;
    }
}
